package coml.zhouxiaoge.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author zhouxiaoge
 * <p>
 * Created by 2022-04-26 23:19
 */
public class DistributeServer {
    private static final String connectString = "192.168.1.11:2181,192.168.1.12:2181,192.168.1.13:2181";
    private static final int sessionTimeout = 2000;
    private final static String parentNode = "/servers";
    private ZooKeeper zooKeeper;

    public void getConnect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, event -> {
        });
    }

    public void registerServer(String hostName) throws InterruptedException, KeeperException {
        String create = zooKeeper.create(parentNode + "/server", hostName.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostName + " is online " + create);
    }

    public void business(String hostName) throws InterruptedException {
        System.out.println(hostName + " is working....");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        DistributeServer distributeServer = new DistributeServer();
        // 1、获取zookeeper连接
        distributeServer.getConnect();
        // 2、利用zookeeper连接注册服务器信息
        distributeServer.registerServer(args[0]);
        // 3、启动业务功能
        distributeServer.business(args[0]);
    }
}
